package com.jkm.boss.service.impl;

import com.google.common.base.Optional;
import com.jkm.boss.service.AdminUserService;
import com.jkm.boss.entity.AdminUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.jkm.boss.dao.AdminUserDao;
import org.springframework.stereotype.Service;
import com.jkm.boss.entity.AdminUserPassport;
import com.jkm.boss.helper.AdminUserSupporter;
import com.jkm.boss.service.AdminUserPassportService;

/**
 * Created by shitou on 17/4/17.
 */
@Slf4j
@Service
public class AdminUserServiceImpl implements AdminUserService  {

    @Autowired
    private AdminUserDao adminUserDao;

    @Autowired
    private AdminUserPassportService adminUserPassportService;


    @Override
    public Optional<AdminUser> getAdminUserById(final long auid) {
        return Optional.fromNullable(adminUserDao.selectById(auid));
    }
    /**
     * {@inheritDoc}
     *
     * @param username
     * @return
     */
    @Override
    public Optional<AdminUser> getAdminUserByName(final String username) {
        return Optional.fromNullable(adminUserDao.selectByUsername(username));
    }

    /**
     * {@inheritDoc}
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public Optional<AdminUserPassport> login(final String username, final String password) {
        final Optional<AdminUser> adminUserOptional = getAdminUserByName(username);
        if (adminUserOptional.isPresent()) {
            final AdminUser adminUser = adminUserOptional.get();
            if (AdminUserSupporter.isPasswordCorrect(adminUser, password)) {
                final AdminUserPassport adminUserToken = adminUserPassportService.generateToken(adminUser.getId());
                return Optional.of(adminUserToken);
            }
        }

        return Optional.absent();
    }

    @Override
    public void logout(final long auid) {
        adminUserPassportService.invalidatePassport(auid);
    }

    /**
     * 最后一次登陆时间
     *
     * @param id
     * @return
     */
    @Override
    public void updateLastLoginDate(long id) {
        adminUserDao.updateLastLoginDate(id);
    }

}
